import { keys, trimEnd, trimStart } from 'lodash-es';
import { join } from 'path-browserify';

import { generateBaseApis } from '@/fierce/api/base-apis';

const apiModules: Recordable<ApiModule> = import.meta.glob('@/api/**/*.ts', {
  eager: true,
  import: 'default',
  exhaustive: false,
});

const computedApis: Recordable<ComputedApiDescriptor> = {};

function computeApi(apis: ApiModule['apis'], basePath: string) {
  for (const api of keys(apis)) {
    computedApis[trimStart(join(basePath, api), '/').replaceAll('/', '.')] = {
      uri: trimEnd(join(basePath, apis[api].uri), '/'),
      method: apis[api].method,
      fixedParams: apis[api].fixedParams,
      fixedData: apis[api].fixedData,
      fixedHeaders: apis[api].fixedHeaders,
      hasPermission: false,
    };
  }
}

for (const key of keys(apiModules)) {
  const apiModule = apiModules[key];

  const basePath = key.replace('/src/api', '').replace('.ts', '');
  computeApi(apiModule.apis, basePath);
  if (apiModule.extendBaseApis) {
    computeApi(generateBaseApis(), basePath);
  }
}

export default computedApis;
